
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.Clinic;
import org.springframework.samples.petclinic.Owner;
import org.springframework.samples.petclinic.validation.OwnerValidator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.bind.WebDataBinder;

import org.groovyflow.spring.locator.*
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.samples.petclinic.validation.*

/**
 * JavaBean form controller that is used to add a new <code>Owner</code> to
 * the system.
 *
 * @author Juergen Hoeller
 * @author Ken Krebs
 */
 //@Configurable doesn't help us get autowiring here!
@Configurable
@Controller
//Don't think this request mapping is actually used!
//@RequestMapping(["/addOwner.gr"])
@SessionAttributes(types = [Owner.class])
public class AddOwnerController {

	def BeanLocator beanLocator = new BeanLocatorImpl();

	//Autowiring doesn't work yet
	private final Clinic clinic;
	
	//Autowiring doesn't work yet
	@Autowired
	public AddOwnerController(Clinic clinic){
		this.clinic = clinic;
	}
	
	def getClinic(){
		return beanLocator.getBean("clinic")
	}
	

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
    	String[] arr = {"id"}
        dataBinder.setDisallowedFields(arr);
    }

    @RequestMapping(method = [RequestMethod.GET])
    public String setupForm(Model model) {
       
		Owner owner = new Owner();
		model.addAttribute(owner);
		return "ownerForm";
	}

	@RequestMapping(method = [RequestMethod.POST])
	public String processSubmit(@ModelAttribute Owner owner, BindingResult result, SessionStatus status) {
		println "Groovy AddOwnerController processSubmit"
		new OwnerValidator().validate(owner, result);
		if (result.hasErrors()) {
			return "ownerForm";
		}
		else {
			//Autowiring doesn't work yet
			//this.clinic.storeOwner(owner);
			this.getClinic().storeOwner(owner);
			status.setComplete();
			return "redirect:owner.do?ownerId=" + owner.getId();
		}
	}

}

